import { HttpException, Injectable } from '@nestjs/common'
import { InjectRepository } from '@nestjs/typeorm'
import { In, LessThanOrEqual, Repository } from 'typeorm'
import { OrderEntity } from './entities/order.entity'
import { ListOrderDto } from './dto/list-order.dto'
import { handleTimeRange } from '@/utils'
import { delOrderDto } from './dto/del-order.dto'

@Injectable()
export class OrderService {
  constructor(
    @InjectRepository(OrderEntity)
    private readonly orderRepository: Repository<OrderEntity>,
  ) { }

  // 订单list
  async orderList(userId: number, data: ListOrderDto) {
    const qb = this.orderRepository.createQueryBuilder('order')
    // 关联查询订单详情-子表
    qb.leftJoinAndSelect('order.items', 'orderItem')
    qb.leftJoinAndSelect('order.refund', 'refund')
    qb.where('order.user_id = :userId AND order.is_del = 0', { userId }).orderBy('order.create_time', 'DESC')

    // 添加状态过滤
    if (data.status) {
      qb.andWhere('order.status = :status', { status: data.status })
    }
    // 添加时间范围过滤
    handleTimeRange(qb, 'order', 'create_time', 'start', 'end', data)

    // 处理分页参数
    if (data.page && data.pageSize) {
      const page = Number(data.page) || 1
      const pageSize = Number(data.pageSize) || 10
      qb.skip((page - 1) * pageSize).take(pageSize)
    }

    const [orders, total] = await qb.getManyAndCount()
    const temp = orders.map((order) => {
      // 提取退款记录（可能为null，因为不是所有订单都有退款）
      const refund = order.refund || []

      return {
        ...(({ user_id, is_del, refund, ...rest }) => rest)(order),
        remark: order.remark,
        // 退款相关备注
        refundInfo: {
          userRemark: refund[0]?.user_remark || '',
          merchantRemark: refund[0]?.merchant_remark || ''
        }
      }
    })

    return {
      entries: temp,
      total
    }
  }

  // 删除订单
  async delete(userId: number, data: delOrderDto) {
    const order = await this.orderRepository.findOne({
      where: {
        id: data.id,
        user_id: userId,
        is_del: 0
      }
    })
    if (!order) throw new HttpException('订单不存在或已删除', 404)

    await this.orderRepository.update(
      { id: data.id },
      { is_del: 1 }
    )
    return order
  }

  // 完成用餐
  async finishMeal(orderId: number, userId: number) {
    const order = await this.orderRepository.findOne({
      where: {
        id: orderId,
        user_id: userId,
        status: 1,
        is_del: 0
      }
    })
    if (!order) throw new HttpException('订单不存在或状态不符合要求（需为已付款状态）', 409)
    order.status = 2
    return this.orderRepository.save(order)
  }
}
